import React from 'react'
import {Link, useMatch, useResolvedPath} from 'react-router-dom'
import type {LinkProps} from 'react-router-dom'

interface NavLinkProps extends LinkProps {
  activeStyle?: React.CSSProperties
}

export default function NavLink({ children, to, activeStyle, ...props }: NavLinkProps) {
  const resolved = useResolvedPath(to)
  const match = useMatch({ path: resolved.pathname, end: true })

  return (
    <Link style={match ? activeStyle : {}} to={to} {...props}>
      {children}
    </Link>
  )
}